Welcome to JavaScript!

7.16 事件监听

1、addEventListener()添加事件监听

语法:对象.addEventListener(“事件名”,执行函数名,布尔值(可选))

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<style>

#laoLiu{

width:300px ; height:100px; line-height:30px; text-align:center ;

background:burlywood;margin:0 auto;

color:blue;font-size:24px;

}

</style>

<script type="text/javascript">

function abc(){

document.getElementById("laoLiu").innerText=Math.random();

};

window.onload=function(){

var z=document.getElementById("laoLiu");

x=z.addEventListener("click",abc) //第一个参数的事件,不用在前面加“on”;第二个参数是函数名,不需要加括号

};

};

</script>

</head>

<body>

<div id="laoLiu" >我要学习</div>

</body>

</html>

结果同上一节

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<style>

#laoLiu{

width:300px ; height:100px; line-height:30px; text-align:center ;

background:burlywood;margin:0 auto;

color:blue;font-size:24px;

}

</style>

<script type="text/javascript">

function abc(){

// 生成随机小数

t=Math.random();

// 将随机小数保留两位小数

const num = t.toFixed(2);

// 将保留两位小数的字符串转换回数字,并乘以100

const numb=parseFloat(num) * 100;

document.getElementById("laoLiu").innerText=numb

};

function efg(){

document.getElementById("laoLiu").removeEventListener("mousemove",abc);

};

window.onload=function(){

document.getElementById("laoLiu").addEventListener("mousemove",abc);

document.getElementById("laoLiu").addEventListener("click",efg);

//此程序会导致:鼠标移入标签元素位置内会触发随机函数,当鼠标停止时,随机函数会显示一个获得的结果值不变,当鼠标再次移到时,

//就会就断触发随机函数的不断运行,当点击鼠标时,随机函数中止运行,并且会得到一个永不再改变的数,

//这个场景可以应该抽奖情景。

};

</script>

</head>

<body>

<div id="laoLiu" >我要学习</div>

</body>

</html>